<template>
  <div class="info-main">
    <div class="flex">
      <div class="flex1"></div>
      <el-button type="primary" plain @click="submitForm">提交</el-button>
    </div>
    <el-form ref="ruleForm" :model="form" label-width="100px" :rules="rules" class="main-form">
      <el-form-item label="旧密码" prop="old_pw">
        <el-input type="password" class="main-input" v-model="form.old_pw" autocomplete="new-password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pw">
        <el-input type="password" class="main-input" v-model="form.new_pw" autocomplete="new-password"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="new_pw_again">
        <el-input type="password" class="main-input" v-model="form.new_pw_again" autocomplete="new-password"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { userApi } from '@/api/modules/user.js';
import { ElMessage } from 'element-plus';
import { Decrypt, Encrypt } from '@/utils/encryption';
import { validatePassword } from '@/utils/common';
const form = ref({
  old_pw: '',
  new_pw: '',
  new_pw_again: ''
});

const ruleForm = ref(null);

const validateNewPwAgain = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'));
  } else if (value !== form.value.new_pw) {
    callback(new Error('两次输入的新密码不一致!'));
  } else {
    callback();
  }
};


const rules = ref({
  old_pw: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
  ],
  new_pw: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  new_pw_again: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateNewPwAgain, trigger: 'blur' }
  ]
});

const submitForm = async () => {
  if (!ruleForm.value) return
  try {
    await ruleForm.value.validate()
    userApi.userPasswordSave({
      old_pw: Encrypt(form.value.old_pw),
      new_pw: Encrypt(form.value.new_pw),
      new_pw_again: Encrypt(form.value.new_pw_again)
    }).then(res => {
      ElMessage.success('密码修改成功');
    })
  } catch (error) {
    // ElMessage.error(error);
  }

};
</script>

<style lang="scss" scoped>
.main-form {
  margin: 50px auto 0;
  width: 400px;
  text-align: center;
  cursor: pointer;

  .code {
    font-family: MiSans, MiSans;
    font-weight: 400;
    font-size: 14px;
    color: #33A0FF;
    position: absolute;
    top: 0;
    right: 16px;
  }

  .main-input {
    width: 292px;
    position: relative;
  }
}
</style>